package com.fadis.server;

import com.fadis.cmd.CmdDispatcher;
import com.fadis.utils.SafeEncoder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * CmdHandler
 */
public class CmdHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = (ByteBuf) msg;
        String s = in.toString(CharsetUtil.UTF_8);
        System.out.println("server 收到：" + s.replace("\r\n", "/r/n"));

        String resp = CmdDispatcher.run(s);
        ctx.write(Unpooled.wrappedBuffer(SafeEncoder.encode(resp)));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
